﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class CheckSumPipe : UpdatePipeBase
{
    public CheckSumPipe()
    {
        PipeName = "文件校验";
    }

    protected override Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        if (context.Package is null)
        {
            context.LogError("更新包元数据不存在");
            return Task.CompletedTask;
        }

        var downloadRoot = context.GetDownloadDirectory();

        Func<string, string> hashHandler = context.Package.ChecksumType switch
        {
            EFileChecksumType.MD5 => HashUtils.Md5File,
            EFileChecksumType.SHA1 => HashUtils.Sha1File,
            EFileChecksumType.SHA256 => HashUtils.Sha256File,
            EFileChecksumType.SHA512 => HashUtils.Sha512File,
            _ => throw new UpdaterException("更新元数据中存在不支持的文件校验类型")
        };

        context.LogInformation("开始校验更新文件");
        for (var i = 0; i < context.Package.Files.Count; i++)
        {
            var item = context.Package.Files[i];
            context.LogInformation("开始校验文件：{file}", item.FileUri);
            var fullName = item.GetSavePath(downloadRoot);
            if (!File.Exists(fullName))
            {
                context.LogError($"校验失败，文件不存在：{item.FileUri}");
                return Task.CompletedTask;
            }

            var acturalHash = hashHandler(fullName);

            if (!item.Hash.Equals(acturalHash, StringComparison.Ordinal))
            {                
                context.LogError($"校验失败：{item.FileUri}");
                return Task.CompletedTask;
            }
            context.ReportProgress(i + 1, context.Package.Files.Count);
        }
        context.LogInformation("校验更新文件成功");
        return Task.CompletedTask;
    }
}
